import { Injectable, ExecutionContext, CanActivate } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Request } from "express";
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get("roles", context.getHandler());
    //如果没有为此路由处理函数设置角色 那表示此路由可以被任何人访问
    if (!roles) {
      return true;
    }
    //返回获取当前的请求对象
    const request = context.switchToHttp().getRequest<Request>();
    const user = { roles: [request.query.role] };
    // const user = { id: 1, name: "nick", role: request.query.role };
    return matchRoles(roles, user.roles);
  }
}

function matchRoles(roles, userRoles) {
  return userRoles.some((role) => roles.includes(role));
}
